package com.troila.cloud.simplify.web.controller.rest;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.troila.cloud.simplify.service.FileService;

import net.coobird.thumbnailator.Thumbnails;

@RestController
@RequestMapping("/api/file")
public class FileController {
	private static final Logger LOGGER = LoggerFactory.getLogger(FileService.class);

	@Autowired
	private FileService fileService;
	
	@Value("${attachment.rootFolder}")
	private String image_path;
    
	/**
	 * 
	 * 图片上传api
	 *
	 * @author wangxuewei
	 */
	@PostMapping("/uploadFile")
	public ResponseEntity<String> uploadFile(HttpSession session,
			@RequestParam("file") MultipartFile file) {
		
		return ResponseEntity.ok(fileService.uploadFile(session, file));
	}
	
	//显示图片的方法关键 匹配路径像 localhost:8080/b7c76eb3-5a67-4d41-ae5c-1642af3f8746.png  
    @RequestMapping(method = RequestMethod.GET, value = "/{filename:.+}")  
    @ResponseBody  
    public void getFile(@PathVariable String filename,HttpServletResponse resp,HttpServletRequest req) {  
		BufferedInputStream is = null;
		try {
			is = new BufferedInputStream(new FileInputStream(image_path+filename));
			OutputStream os = resp.getOutputStream();
			byte[] buffer = new byte[4096];
			while(is.read(buffer) > 0) {
				os.write(buffer);
				os.flush();
			}
		} catch(Exception e) {
			LOGGER.error("文件下载【{}】异常：{}", filename, e.getMessage(), e);
		} finally {
			if(is != null) {
				try {
					is.close();
				} catch(IOException e) {
				}
			}
		}
    }
    public static void main(String[] args) {
    	String uuid = UUID.randomUUID().toString().replaceAll("-", "");
    	System.out.println(uuid);
	}
}
